//
//  LYViewController.m
//  LYDevelopKit
//
//  Created by liyang on 05/26/2018.
//  Copyright (c) 2018 liyang. All rights reserved.
//

#import "LYViewController.h"
#import <LYProgressHUD.h>
#import <UITextField+LYAdd.h>

#import <LYTabBarController.h>
#import <NSString+LYAdd.h>
#import <YTKNetwork.h>

#import <LYDevelopKit+Foundation.h>

#import <LYDebug.h>

#import <UIFont+LYAdd.h>

#import <LYBarHUD.h>

#import <UIKit/UIFeedbackGenerator.h>

#import <pthread.h>

#import "LYInject.h"

@interface LYViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *textField;


@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UIButton *button;

/// <#注释#>
@property (nonatomic, strong) UIImpactFeedbackGenerator *generator;

@property (nonatomic, strong) NSMutableArray *commands;

@end

@implementation LYViewController
{
    dispatch_semaphore_t _lock;
}

- (NSMutableArray *)commands
{
    if (_commands) return _commands;
    _commands = [NSMutableArray array];
    return _commands;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    Dog *dog = [[Dog alloc]init];
    [Dog say];
    [dog walk];
    
    People *people = [[People alloc]init];
    [People say];
    [people walk];
    
    
//    BOOL flag = YES;
//    // 1. 检测是不是没有已连接的设备
//    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
//    if (flag)
//    {
//        dispatch_async(dispatch_get_global_queue(0, 0), ^{
//            sleep(2);
//            NSLog(@"释放信号1 %@", [NSThread currentThread]);
//            dispatch_semaphore_signal(semaphore);
//        });
//    }
//    else
//    {
//        NSLog(@"释放信号2");
//        dispatch_semaphore_signal(semaphore);
//    }
//    NSLog(@"等待");
//    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//    
//    NSLog(@"等待结束");
//    _lock = dispatch_semaphore_create(1);
    
    self.label.font = [UIFont iconfontWithSize:30];
//    NSString *icon = @"\U0000e634";
    self.label.text = @"634".iconUnicode;
    [self.label sizeToFit];
    
    [self.button setImage:[UIImage iconWithFontSize:25 unicode:@"634".iconUnicode color:[UIColor orangeColor]] forState:UIControlStateNormal];
    
	// Do any additional setup after loading the view, typically from a nib.
    
//    self.textField.delegate = self;
    
//    self.textField.maxTextLength = 10;
//    [self.textField setBlockOnBreakMaxLength:^(UITextField *textField) {
//        [LYProgressHUD showErrorWithStatus:@"只能输入10个字符"];
//    }];
//
//    self.textField.restrictType = LYRestrictTypeExceptEmoji;
//    [self.textField setBlockOnBreakRestrict:^(UITextField *textField) {
//        [LYProgressHUD showErrorWithStatus:@"不能输入表情符号"];
//    }];
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (string.length == 0) return YES;
    
    if (string.containsEmoji && !string.containsSudokuNumber)
    {
        return NO;
    }
    
    NSInteger existedLength = textField.text.length;
    NSInteger selectedLength = range.length;
    NSInteger replaceLength = string.length;
    if (existedLength - selectedLength + replaceLength > 10)
    {
        [LYProgressHUD showErrorWithStatus:@"只能输入10个字符"];
        return NO;
    }
    
    return YES;
}



- (void)setupNetworkModule
{
    NSTimeInterval millsecond = [[NSDate date] timeIntervalSince1970];
    NSString *seq = [NSString stringWithFormat:@"%.0f",millsecond * 1000];
    YTKNetworkAgent *agent = [YTKNetworkAgent sharedAgent];
    [YTKNetworkAgent registerEnrtyForRequest:[self class]];
    NSDictionary *headers = @{
                              @"deviceType":@"Neutral007",
                              @"SystemVersion": @"11.3.1",
                              @"clientType": @"iphone",
                              @"customerCode": @"appscomm",
                              @"phoneType": @"iPhone 6S Plus",
                              @"seq": seq
                              };
    NSMutableDictionary *argument = [NSMutableDictionary dictionaryWithDictionary:headers];
    [argument addEntriesFromDictionary:@{@"versionNo":@"1.0.7",
                                         @"productCode": @"W007G",
                                         @"language": @201,
                                         @"accountId": @"zhongxing12@163.com",
                                         @"password": @"123456"
                                         }];
    agent.requestArgument = argument;
    [YTKNetworkConfig sharedConfig].baseUrl = @"https://testnew.appscomm.cn/";
    agent.requestHeaderFields = headers;
    [agent addValue:@"application/json" forHeaderField:@"Content-Type"];
    [agent addValue:@"201" forHeaderField:@"language"];
    [agent addValue:seq forHeaderField:@"accessSeq"];
    
    [agent addLocalizedDescription:@"account and password not match" forResponseCode:2018];
    //    [agent addValue:@"3fa9311b9dde389a0d3cee390b92d2debf8373dd555a0e259294de635ed0c50b" forHeaderField:@"accessToken"];
    //    [agent addValue:@"application/json" forHeaderField:@"Content-Type"];
}
/// 请求的统一入口回调
+ (void)enrtyForRequest:(__kindof YTKBaseRequest *)requset error:(NSError *__autoreleasing*)error
{
    NSDictionary *dic = requset.responseObject;
    NSInteger code = [dic[@"code"] integerValue];
    NSString *msg = dic[@"msg"];
    if (msg.length)
    {
        *error = [NSError ytkErrorWithCode:code description:msg];
        return;
    }
    
    
    code = [dic[@"status"] integerValue];
    if (code != 0)
    {
        NSString *msg = dic[@"message"];
        if (msg.length)
        {
            *error = [NSError ytkErrorWithCode:code description:msg];
        }
    }
}

/// 收到特定错误码的回调
+ (void)request:(__kindof YTKBaseRequest *)requset didEndWithErrorCode:(NSInteger)code
{
    NSLog(@"-------  %ld", code);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [LYBarHUD presentErrorWithStatus:@"这是一条提示语"];
}
- (IBAction)info:(id)sender
{
    NSLog(@"%@", [NSThread currentThread]);
//    [LYBarHUD presentInfoWithStatus:@"这是一条提示语"];
//    dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER);
    [self performSelectorInBackground:@selector(remove) withObject:nil];
}

- (IBAction)info1:(id)sender
{
    NSLog(@"%@", [NSThread currentThread]);
    [self remove];
}

- (void)remove
{
    NSLog(@"%@", [NSThread currentThread]);
//    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"dispatch remove");
        for (NSNumber *index in self.commands)
        {
            NSLog(@"%@", index);
        }
        [self.commands removeAllObjects];
//        dispatch_semaphore_signal(semaphore);
    });
//    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    NSLog(@"remove");
    [self.commands removeAllObjects];
}

static NSInteger commandIndex = 0;
- (IBAction)btnAction:(id)sender
{
    NSLog(@"添加%ld", commandIndex);
    [self.commands addObject:@(commandIndex)];
    commandIndex++;
//    _generator = [[UIImpactFeedbackGenerator alloc]initWithStyle:UIImpactFeedbackStyleMedium];
//    [_generator impactOccurred];
    
//    [LYProgressHUD showInfoWithStatus:@"info"];
//    [LYBarHUD presentInfoWithStatus:@"这是一条提示语"];
//    [LYBarHUD presentErrorWithStatus:@"这是一条提示语"];
//    [LYBarHUD setStayInterval:4];
//    [LYBarHUD presentSuccessWithStatus:@"这是一条提示语"];
    
//    [LYBarHUD presentAlertWithStatus:@"这是一条提示语"];
//    [LYBarHUD presentCustomWithImage:[UIImage imageNamed:@"alert"] status:@"这是一条警告"];
//    [LYBarHUD setTextAlignment:NSTextAlignmentCenter];
//    [LYBarHUD setFont:[UIFont systemFontOfSize:10]];
//    [LYBarHUD presentCustomWithImage:nil status:@"这是一条警告"];
    return;
    
    [LYProgressHUD showLoading];
    LYRequest *request = [[LYRequest alloc]init];
//    request.requestSerializerType = YTKRequestSerializerTypeJSON;
    request.method = YTKRequestMethodPOST;
    request.argument = @{
                         @"accountId": @"zhongxing12@163.com",
                         @"password": @"123456",
                         };
    request.urlPath = @"account/login";
    
//    [request setCompletePreprocessor:^(LYRequest *request) {
//        NSLog(@"Preprocessor--%@", [NSThread currentThread]);
//    }];
//
//    [request setCompleteFilter:^(LYRequest *request) {
//        NSLog(@"Filter -- %@", [NSThread currentThread]);
//    }];
    
//    [request setResponseValidateBlock:^(__kindof YTKBaseRequest * _Nonnull request, NSError * _Nullable __autoreleasing * _Nullable error) {
////        NSLog(@"");
//        *error = [NSError ytkErrorWithCode:2017 description:@"password error"];
//    }];
    
//    request.successCodeSet = @[@0, @2018];
//    request.errorCodeSet = @[@2018];
    
//    request.cacheTimeInSeconds = 30;
//    request.urlPath = @"http://itunes.apple.com/lookup?id=1254313578";
    [request startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [LYProgressHUD showSuccessWithStatus:@"success"];
        NSLog(@"success");
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [LYProgressHUD showErrorWithStatus:@"failure"];
        NSLog(@"%@", request.error);
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)textField:(id)sender {
}
@end
